package org.jeecg.modules.workflow.framework.activiti.core.behavior.script.impl;

import com.boc.ewr.util.SysRoleEnum;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.runtime.ProcessInstance;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.util.collection.SetUtils;
import org.jeecg.modules.workflow.enums.definition.BpmTaskRuleScriptEnum;
import org.jeecg.modules.workflow.framework.activiti.core.behavior.script.BpmTaskAssignScript;
import org.jeecg.modules.workflow.service.task.BpmProcessInstanceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.Set;

/**
 * @author : Wzz
 * @create : 2023-06- 15- 17:28
 * @desc :分配给省行非本人用户审批的 Script 实现类
 */
@Component
public class BpmTaskAssignAdminNoMeScript implements BpmTaskAssignScript {

    @Resource
    @Lazy // 解决循环依赖
    private BpmProcessInstanceService bpmProcessInstanceService;

    @Autowired
    private ISysBaseAPI sysBaseAPI;

    @Override
    public Set<String> calculateTaskCandidateUsers(DelegateExecution execution) {
        ProcessInstance processInstance = bpmProcessInstanceService.getProcessInstance(execution.getProcessInstanceId());
        String userId = processInstance.getStartUserId();
        // 获取 省行对账复核 角色Id
        String roleIdCheck = sysBaseAPI.getRoleIdByRoleCode(SysRoleEnum.ADMIN_CA_CHECK.getCode());
        // 获取 省行对账操作员 角色Id
        String roleIdHandler = sysBaseAPI.getRoleIdByRoleCode(SysRoleEnum.ADMIN_CA_HANDLER.getCode());

        String[] ids = new String[]{roleIdCheck, roleIdHandler};
        Set<String> adminAllByUserId = new HashSet<>(sysBaseAPI.queryUserIdsByRoleIds(ids));
        adminAllByUserId.remove(userId);
        if (adminAllByUserId != null && adminAllByUserId.size() > 0) {
            return adminAllByUserId;
        }
        // 如果没有用户则返回管理员
        return SetUtils.asSet(sysBaseAPI.getLoginUserByUserName("admin").getId());
    }

    @Override
    public BpmTaskRuleScriptEnum getEnum() {
        return BpmTaskRuleScriptEnum.PARENT_BRANCH_OTHER;
    }
}
